<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :image-field="formInfo.imageField"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            :list-type-info="listTypeInfo"
          >
            <template v-slot:form-deviceTypeValue>
              <el-input
                v-model="formInfo.data.deviceTypeValue"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择医疗器械分类目录"
              >
                <template #append>
                  <el-icon @click="openDeviceTypeWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
            <!--资产分类-->
            <template v-slot:form-brandName>
              <el-input
                v-model="formInfo.data.brandName"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择厂家"
              >
                <template #append>
                  <el-icon @click="openBrandNameWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-accessoriesCategoryValue>
              <el-input
                v-model="formInfo.data.accessoriesCategoryValue"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择配件分类"
              >
                <template #append>
                  <el-icon @click="openAccessoriesCategoryWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
    </NewFullScreen>

    <SelectBrand
      v-if="selectBrandInfo.visible"
      v-model:showDialog="selectBrandInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectBrandCallBack"
    />

    <SelectSettingClassification
      v-if="selectSettingClassificationInfo.visible"
      v-model:showDialog="selectSettingClassificationInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectSettingClassificationInfoCallBack"
    />

    <SelectSettingAccessories
      v-if="selectSettingAccessoriesInfo.visible"
      @callback="selectAccessioresCategoryCallBack"
      :saveEmpty="true"
      :query="selectSettingAccessoriesInfo.query"
      v-model:showDialog="selectSettingAccessoriesInfo.visible"
    />
  </div>
</template>

<script setup name="equipmentArchivesModify">
import utils from '@/common/js/utils' // 公共方法

import PageForm from '@/components/PageForm/index'
import {
  detailAccessoriesArchives,
  createAccessoriesArchives,
  updateAccessoriesArchives,
} from '@/api/equipment'
import { getCoreCodeStatus } from '@/api/core'
import axios from 'axios'
import SelectBrand from '@/components/SelectBrand/index'
import SelectSettingClassification from '@/components/SelectSettingClassification/index'
import SelectSettingAccessories from '@/components/SelectSettingAccessories/index'
import { getUnitAll } from '@/api/core'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
})

const formInfo = ref({
  ref: null,
  data: {},
  imageField: {
    label: '配件照片',
    value: 'pictureList',
    fileType: ['jpg', 'png'],
    fileSize: 1,
    action: axios.defaults.baseURL + '/pub/uploadfile',
  },
  fieldList: [
    {
      label: '配件名称',
      value: 'commonName',
      type: 'input',
    },
    { label: '配件编码', value: 'code', type: 'input' },
    {
      label: '单价',
      value: 'referencePrice',
      type: 'money',
      rules: { validator: proxy.$validate.positiveMoney, trigger: 'blur' },
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'enabled_type',
    },
    {
      label: '医疗器械分类目录',
      value: 'deviceTypeValue',
      type: 'slot',
    },
    {
      label: '计量单位',
      value: 'unitId',
      type: 'select',
      required: false,
      list: 'unitList',
      filterable: true,
    },
    {
      label: '品牌',
      value: 'trademark',
      type: 'input',
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
    },
    {
      label: '生产厂家',
      value: 'brandName',
      type: 'slot',
    },
    {
      label: '配件分类',
      value: 'accessoriesCategoryValue',
      type: 'slot',
    },
    { label: '配件简称', value: 'alias', type: 'input' },
    { label: '外部系统标识', value: 'mnemonic', type: 'input' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    commonName: [
      { required: true, message: '请输入配件名称', trigger: 'change' },
    ],
    code: [
      { required: true, message: '请输入配件编码', trigger: 'change' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})

const selectBrandInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectSettingAccessoriesInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const listTypeInfo = ref({
  licenseList: [],
  brandList: [],
  unitList: [],
})
const selectSettingClassificationInfo = ref({
  visible: false,
  query: {
    status: '1',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})

onMounted(() => {
  getUnitList()
  getStatus()
  if (props.id) {
    getDeatil()
  }
})

const getDeatil = () => {
  detailAccessoriesArchives(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      formInfo.value.data = {
        commonName: data.commonName,
        code: data.code,
        unitId: data.unitId == -2 ? '' : data.unitId,
        unitName: data.unitName,
        standard: data.standard,
        status: data.status,
        statusValue: data.statusValue,
        remark: data.remark,
        trademark: data.trademark,
        alias: data.alias,
        mnemonic: data.mnemonic,
        accessoriesCategory: data.accessoriesCategory,
        accessoriesCategoryValue: data.accessoriesCategoryValue,
        brandId: data.brandId,
        brandName: data.brandName,
        picture: data.picture,
        deviceType: data.deviceType,
        deviceTypeValue: data.deviceTypeValue,
        createUser: data.createUser,
        createTime: data.createTime,
        orgId: data.orgId,
        referencePrice: data.referencePrice,
      }

      if (formInfo.value.data.picture) {
        formInfo.value.data.pictureList = utils.splitArr(
          formInfo.value.data.picture
        )
      }
    }
  })
}
const save = async () => {
  let flag = 0
  await formInfo.value.ref.validate((valid) => {
    if (valid) {
      console.log(valid, 'formOrgInfo.ref.validate')
      flag++
    }
  })
  console.log(flag)
  if (flag == 1) {
    console.log(flag)
    const requestData = formInfo.value.data
    if (requestData.pictureList && requestData.pictureList.length == 1) {
      requestData.picture = requestData.pictureList[0]
    } else {
      requestData.picture = ''
    }
    if (props.id) {
      requestData.id = props.id
    }
    const api = props.id ? updateAccessoriesArchives : createAccessoriesArchives
    console.log(api)
    api(requestData).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify')
        formInfo.value.ref.validateField()
      }
    })
  }
}
const handleResponse = (response) => {
  return response
}
// 选择征照
const selectAccessioresCategoryCallBack = (row) => {
  if (row) {
    formInfo.value.data.accessoriesCategory = row.id
    formInfo.value.data.accessoriesCategoryValue = row.name
  } else {
    formInfo.value.data.accessoriesCategory = '-2'
    formInfo.value.data.accessoriesCategoryValue = ''
  }
}
const selectBrandCallBack = (row) => {
  if (row) {
    formInfo.value.data.brandId = row.id
    formInfo.value.data.brandName = row.name
  } else {
    formInfo.value.data.brandId = '-2'
    formInfo.value.data.brandName = ''
  }
}
const selectSettingClassificationInfoCallBack = (row) => {
  if (row) {
    formInfo.value.data.deviceType = row.id
    formInfo.value.data.deviceTypeValue = row.name
  } else {
    formInfo.value.data.deviceType = '-2'
    formInfo.value.data.deviceTypeValue = ''
  }
}
//获取计量单位列表
const getUnitList = () => {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
const openDeviceTypeWindow = () => {
  selectSettingClassificationInfo.value.visible = true
}
const openBrandNameWindow = () => {
  selectBrandInfo.value.visible = true
}
const openAccessoriesCategoryWindow = () => {
  selectSettingAccessoriesInfo.value.visible = true
}
const getStatus = () => {
  getCoreCodeStatus({ codeType: '9' }).then((res) => {
    showFieldListItem(!res.data, 'code')
    formInfo.value.rules.code[1].required = !res.data
  })
}
const showFieldListItem = (show, nameValue) => {
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}

.inputScan {
  ime-mode: disabled;
}

.active {
  display: none;
}
</style>
